package com.fbs.wowo.util.dbutils;

import com.fbs.wowo.util.common.Constants;
import com.mongodb.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

import java.util.ArrayList;
import java.util.List;

public class MongoConfig {

    private static final String HOST = Constants.getEosMongodbHost();

    private static final String dbName = Constants.getEosMongodbDbname();

    private static MongoClient mongo;
    private static MongoDatabase db;

    private static int maxConnect = 50;
    private static int maxWaitThread = 50;
    private static int maxTimeOut = 60;
    private static int maxWaitTime = 60;
    private static String username = "eosro";
    private static String password = "eosro";

    static {
        MongoClientOptions.Builder build = new MongoClientOptions.Builder();
        build.connectionsPerHost(Integer.valueOf(maxConnect));
        build.threadsAllowedToBlockForConnectionMultiplier(Integer.valueOf(maxWaitThread));
        build.connectTimeout(Integer.valueOf(maxTimeOut) * 1000);
        build.maxWaitTime(Integer.valueOf(maxWaitTime) * 1000);
        MongoClientOptions options = build.build();

        try {
            //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
            //ServerAddress()两个参数分别为 服务器地址 和 端口
            ServerAddress serverAddress = new ServerAddress(HOST,27017);
            List<ServerAddress> addrs = new ArrayList<ServerAddress>();
            addrs.add(serverAddress);

            //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
            MongoCredential credential = MongoCredential.createScramSha1Credential(username, dbName, password.toCharArray());

            //通过连接认证获取MongoDB连接
            mongo = new MongoClient(addrs,credential, options);
            db = mongo.getDatabase(dbName);
        } catch (MongoException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取集合(表)
     *
     * @param collectionName
     * @return
     */
    public static MongoCollection getCollection(String collectionName) {
        return db.getCollection(collectionName);
    }
}
